/*
 * Copyright (C) 2014 Wei Chou (weichou2010@gmail.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.wei.c.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.widget.FrameLayout;

import com.wei.c.lib.R;

/**
 * 可设置纵横比的FrameLayout，并可以设置是基于width来算height，还是基于height来算width.
 * 
 * @author 周伟 Wei Chou(weichou2010@gmail.com)
 */
public class AspectRadioFrameLayout extends FrameLayout {
	public static final int BASE_ON_WIDTH		= 0;
	public static final int BASE_ON_HEIGHT		= 1;
	private float mAspectRadio;
	private int mAspectBaseOn = BASE_ON_HEIGHT;

	public AspectRadioFrameLayout(Context context) {
		super(context);
	}

	public AspectRadioFrameLayout(Context context, AttributeSet attrs) {
		this(context, attrs, 0);
	}

	public AspectRadioFrameLayout(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);

		TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.AspectRadioFrameLayout, defStyle, 0);
		setAspectRadio(a.getFloat(R.styleable.AspectRadioFrameLayout_aspectRadio, 0));
		setAspectBaseOn(a.getInt(R.styleable.AspectRadioFrameLayout_aspectBaseOn, BASE_ON_HEIGHT));
		a.recycle();
	}

	public void setAspectRadio(float aspectRadio) {
		if (aspectRadio != mAspectRadio) {
			mAspectRadio = aspectRadio;
			requestLayout();
		}
	}

	public void setAspectBaseOn(int aspectBaseOn) {
		if (aspectBaseOn != mAspectBaseOn) {
			mAspectBaseOn = aspectBaseOn;
			requestLayout();
		}
	}

	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		if (mAspectRadio > 0) {
			if (mAspectBaseOn == BASE_ON_HEIGHT) {
				super.onMeasure(MeasureSpec.makeMeasureSpec(
						(int)(MeasureSpec.getSize(heightMeasureSpec) * mAspectRadio),
						MeasureSpec.getMode(heightMeasureSpec)),
						heightMeasureSpec);
			} else {
				super.onMeasure(widthMeasureSpec,
						MeasureSpec.makeMeasureSpec(
								(int)(MeasureSpec.getSize(widthMeasureSpec) * mAspectRadio),
								MeasureSpec.getMode(widthMeasureSpec)));
			}
		} else {
			super.onMeasure(widthMeasureSpec, heightMeasureSpec);
		}
	}
}
